//
//  RechargeViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/8/1.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "RechargeViewController.h"
#import "AssetRecordsViewController.h"
#import "CheckVersionAlearView.h"
@interface RechargeViewController ()
@property(strong,nonatomic)NSArray * array;
@end

@implementation RechargeViewController
- (void)viewDidLayoutSubviews
{
    self.BgView.backgroundColor  =MAINBLACKCOLOR;
    self.BgView.height = UIScreenHeight - kStatusBarAndNavigationBarHeight;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self custonUI];
    [self getrechargeAddress];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem RightitemWithImageNamed:@"" title:Localized(@"Asset_Recharge_record") target:self action:@selector(Record)];
    
}
- (void)getrechargeAddress
{
    WeakSelf
    [self GETWithHost:@"" path:rechargeAddress param:@{@"asset":_assetsName} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
            weakSelf.array = [responseObject[@"result"][@"address"] componentsSeparatedByString:@":"];
            if (weakSelf.array.count>1)
            {
                weakSelf.QRCodeLable.text = weakSelf.array[0];
                weakSelf.QRCodeTitleLable.text = weakSelf.array[1];
                weakSelf.QRCodebutton1.hidden = NO;
            }else
            {
                
                weakSelf.QRCodeLable.text = weakSelf.array[0];
                weakSelf.top.constant +=20;
              
            }
            [weakSelf createQRcodWithUrl:responseObject[@"result"][@"address"]];/*生成二维码*/
        }else
        {
            [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
//充值记录
- (void)Record
{
    AssetRecordsViewController * asset = [[AssetRecordsViewController alloc] init];
    asset.title = Localized(@"Asset_records");
    asset.dataArray = _dataArray;
    [self.navigationController pushViewController:asset animated:YES];
}
- (void)custonUI
{
    
    KViewRadius(_QRCodebutton, 2);
    KViewRadius(_QRCodebutton1, 2);
    _tableview.backgroundColor = TABLEVIEWLCOLOR;
    
    _QRCodebutton1.hidden = YES;
    [_QRCodebutton setTitle:Localized(@"copy") forState:0];
    [_QRCodebutton1 setTitle:Localized(@"copy") forState:0];
    _QRCodeLable.textColor = MAINTITLECOLOR;
     _QRCodeTitleLable.textColor = MAINTITLECOLOR;
    _currencyName.textColor = MAINTITLECOLOR;
    _addressTitle.text = Localized(@"Asset_Long_to_album_message");
    _currencyName.text =  [NSString stringWithFormat:@"%@ %@",_assetsName,Localized(@"Asset_Recharge")];
    _explainLable.text = [NSString stringWithFormat:Localized(@"Asset_Recharge_message"),_assetsName,_assetsName,_assetsName,_assetsName,_assetsName];
    _titleMessage.text = Localized(@"Asset_Recharge_hints");
    //1.创建长按手势
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imglongTapClick:)];
    
    //2.开启人机交互
    self.QRCode.userInteractionEnabled = YES;
    
    //3.添加手势
    [self.QRCode addGestureRecognizer:longTap];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.tableview) {
        CGFloat offY = scrollView.contentOffset.y;
        if (offY < 0) {
            scrollView.contentOffset = CGPointZero;
        }
    }
}
#pragma mark 长按手势弹出警告视图确认
-(void)imglongTapClick:(UILongPressGestureRecognizer*)gesture

{
    
    if(gesture.state==UIGestureRecognizerStateBegan)
        
    {
        CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:Localized(@"Asset_Sure_album") titleStr:Localized(@"Asset_Save_picture") openUrl:@"" confirm:Localized(@"transaction_OK") cancel:Localized(@"transaction_cancel")   state:2 RechargeBlock:^{
            
            // 保存图片到相册
            UIImageWriteToSavedPhotosAlbum(self.QRCode.image,self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
            
            
            
        }];
        
        aleartVC.animationStyle = LXASAnimationDefault;
        [aleartVC showLXAlertView];
        
        
    }
    
}
#pragma mark 保存图片后的回调
- (void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:  (NSError*)error contextInfo:(id)contextInfo
{
    NSString*message =@"呵呵";
    
    if(!error) {
        
        message =Localized(@"Asset_Saved_album");
        
        [EXUnit showSVProgressHUD:message];
        
    }else
        
    {
        
        message = [error description];
        
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"album_message") view:kWindow];
        
    }
    
}
- (void)createQRcodWithUrl:(NSString *)url{
    // 1.创建过滤器
    
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.恢复默认
    
    [filter setDefaults];
    
    // 3.给过滤器添加数据(正则表达式/账号和密码)
    
    //    NSString *dataString = @"http://www.520it.com";
    
    NSData *data = [url dataUsingEncoding:NSUTF8StringEncoding];
    
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 4.获取输出的二维码
    
    CIImage *outputImage = [filter outputImage];
    
    // 5.将CIImage转换成UIImage，并放大显示
    
    self.QRCode.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:100];
    
}
/**
 
 * 根据CIImage生成指定大小的UIImage
 
 *
 
 * @param image CIImage
 
 * @param size 图片宽度
 
 */

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size

{
    
    CGRect extent = CGRectIntegral(image.extent);
    
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    CGContextRelease(bitmapRef);
    
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (IBAction)QRCodebutton:(UIButton *)sender {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    
    pasteboard.string = self.QRCodeLable.text;
    [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Copy_to_paste") view:self.view];
    
}

- (IBAction)copyAddress:(UIButton *)sender {
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    
    pasteboard.string = self.QRCodeTitleLable.text;
    [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Copy_to_paste") view:self.view];
}
@end
